package com.etoak.car.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.etoak.car.bean.Car;
import com.etoak.car.bean.Types;
import com.etoak.car.bean.Users;
import com.etoak.car.bean.vo.ReqPage;
import com.etoak.car.service.CarService;
import com.etoak.commons.PicProperties;
import com.etoak.commons.enums.ETEnums;
import com.etoak.commons.page.Page;
import com.etoak.commons.redis.RedisUtil;
import com.etoak.commons.response.ETResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

@Controller
@Slf4j
@RequestMapping("/car")
public class CarController {

    @Autowired
    private CarService service;

    @Autowired
    PicProperties picProperties;

    @PostMapping("/querySome")
    @ResponseBody
    public ETResponse querySome(@RequestBody ReqPage reqPage){
        /*System.out.println(token);
        RedisUtil ru = RedisUtil.getRedisUtil();
        String userInfo = ru.get(token);
        Users u = JSONObject.parseObject(userInfo, Users.class);
        System.out.println(u.getId());*/
        //获取当前时间

        Page<Car> cars = service.querySome(reqPage.getPageNum(), reqPage.getPageSize(),reqPage.getName());
        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData(cars);
        return response;
    }

    /**
     * 根据id拿取车辆信息
     *
     * @return
     */
    @PostMapping()
    @ResponseBody
    public ETResponse queryCarById(String carId){

        Car car = service.queryCarById(carId);
        ETResponse response = new ETResponse();
        if(car!=null){
            response.setCode(ETEnums.SUCCESS.getCode());
            response.setMsg(ETEnums.SUCCESS.getMsg());
            response.setData(car);
        }else {
            response.setCode(ETEnums.ERROR.getCode());
            response.setMsg(ETEnums.ERROR.getMsg());
            response.setData("修改失败");
        }
        return response;
    }

    /**
     * 修改车辆信息
     *
     * @return
     */
    @PutMapping()
    @ResponseBody
    public ETResponse updateCar(Car car){

        int flag = service.updateCar(car);
        ETResponse response = new ETResponse();
        if(flag>0){
            response.setCode(ETEnums.SUCCESS.getCode());
            response.setMsg(ETEnums.SUCCESS.getMsg());
            response.setData("修改成功");
        }else {
            response.setCode(ETEnums.ERROR.getCode());
            response.setMsg(ETEnums.ERROR.getMsg());
            response.setData("修改失败");
        }
        return response;
    }

    /**
     * 删除车辆信息
     * @param
     * @return
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public ETResponse delCar(@PathVariable String id){

        int flag = service.delCar(id);
        ETResponse response = new ETResponse();
        if(flag>0){
            response.setCode(ETEnums.SUCCESS.getCode());
            response.setMsg(ETEnums.SUCCESS.getMsg());
            response.setData("修改成功");
        }else {
            response.setCode(ETEnums.ERROR.getCode());
            response.setMsg(ETEnums.ERROR.getMsg());
            response.setData("修改失败");
        }
        return response;
    }
    @RequestMapping("/queryType")
    @ResponseBody
    public ETResponse queryCarType(){
        List<Types> type = service.queryCarType();
        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData(type);
        return response;

    }
    //添加类类型
    @RequestMapping("/addType")
    @ResponseBody
    public ETResponse addType(String name,String status){
        service.addType(name,status);
        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData("添加成功");
        return response;
    }
    //删除类类型
    @GetMapping("/{typeId}")
    @ResponseBody
    public ETResponse delType(@PathVariable int typeId){

        service.delType(typeId);
        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData("s删除成功");
        return response;
    }

    //修改类类型
    @RequestMapping("/updateType")
    @ResponseBody
    public ETResponse addType(int id,String name,String status){
        service.updateType(id,name,status);
        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData("添加成功");
        return response;
    }


    @RequestMapping("/upload")
    @ResponseBody
    public ETResponse upload(MultipartFile file){
        ETResponse response = new ETResponse();
        //为空  大小为0 都不符合
        if(ObjectUtils.isEmpty(file) || file.getSize()<=0){
            response.setMsg(ETEnums.ERROR.getMsg());

            return response;

        }
        //拿取文件名称
        String originalFilename = file.getOriginalFilename();
        //拿到名字.后结尾的
        String suffix = FilenameUtils.getExtension(originalFilename);
        if(!StringUtils.equals("JPG",suffix.toUpperCase()) && !StringUtils.equals("PNG",suffix.toUpperCase())){
            response.setMsg(ETEnums.ERROR.getMsg());

            return response;
        }

        //创建新的文件名字
        String uuid = UUID.randomUUID().toString().replace("-","");

        //组合成新的文件名字
        String filename = String.format("%s%s%s",uuid,".",suffix);
        //文件上传路径
        File uploadDir = new File(picProperties.getLocation());
        //没有文件夹就创建
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        //目标文件
        File destFile = new File(uploadDir,filename);

        //执行上传
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            response.setMsg(ETEnums.ERROR.getMsg());

            return response;
        }
        String prefix = picProperties.getMapping();
        String picPath = prefix.endsWith("/") ? prefix + filename : prefix + "/" + filename;
        log.info("图片访问路径 {}",picPath);
        response.setData(picPath);
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        return response;

    }

    @RequestMapping("/addCar")
    @ResponseBody
    public ETResponse addCar(@RequestBody Car car){
        //获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long nowTime = System.currentTimeMillis();
        String time = sdf.format(nowTime);
        car.setZudate(time);
        car.setStatus(0);

        service.addCar(car);
        ETResponse response = new ETResponse();
        response.setCode(ETEnums.SUCCESS.getCode());
        response.setMsg(ETEnums.SUCCESS.getMsg());
        response.setData("成功");
        return response;
    }
}
